<template>
  <a-modal
    :visible="visible"
    title="拖动进行排序"
    :ok-text="'确认保存'"
    :confirm-loading="confirmLoading"
    @cancel="onClose"
    @ok="handleSubmit"
  >
    <draggable :list="sortArray" class="changeGhost" ghost-class="ghost">
      <li v-for="(element, index) in sortArray" :key="index" class="changeDiv">
        {{ index + 1 }}. {{ element.label }}
      </li>
    </draggable>
  </a-modal>
</template>

<script>
export default {
  components: {
    draggable: () => import("vuedraggable"),
  },
  model: {
    //event:什么时候触发v-model行为
    event: "change-visible",
    // 定义传递给v-model的那个变量，绑定到哪个属性值上
    prop: "visible",
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Array,
      default: () => {
        return []
      },
    },
    keys: {
      type: Object,
      default: () => {
        return {
          label: "label",
        }
      },
    },
  },
  data() {
    return {
      buttonCol: { span: 14, offset: 4 },
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      confirmLoading: false,

      sortArray: this.data,
    }
  },
  watch: {
    visible: function (showFlag) {
      if (showFlag) this.pageInit()
    },
  },
  methods: {
    onClose() {
      this.$emit("change-visible", false)
    },
    pageInit() {
      if (this.data.length <= 0) {
        this.$message.error("无排序信息")
        this.onClose()
        return
      }
      this.sortArray = []
      this.data.forEach((item, index) => {
        let tmp = {
          ...item,
          index: index + 1,
        }
        for (let k in this.keys) {
          if (tmp[this.keys[k]]) tmp[k] = tmp[this.keys[k]]
        }
        this.sortArray.push(tmp)
      })
    },
    handleSubmit() {
      this.$emit("change", this.sortArray)
      this.onClose()
    },
  },
}
</script>

<style lang="less" type="text/less" scoped>
.changeGhost li {
  list-style: none;
  padding: 6px;
}
.changeGhost li:nth-child(2n-1) {
  background: #f8f8f8;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb !important;
}
.changeDiv {
  cursor: pointer;
}
</style>
